package com.baofu.paycore.service.processor.transfer;

import com.baofu.paycore.common.exception.PayCoreBizException;
import com.baofu.paycore.common.utils.Constant;
import com.baofu.paycore.manager.model.FreezeBO;
import com.baofu.paycore.manager.model.TransferBO;
import com.baofu.paycore.manager.storer.FreezeOrderRepository;
import com.baofu.paycore.service.converter.DTO2BOConverter;
import com.baofu.paycore.service.facade.enums.PayCoreErrorCode;
import com.baofu.paycore.service.facade.enums.PayStatusEnums;
import com.baofu.paycore.service.facade.model.transfer.UnfreezeTransferDTO;
import com.baofu.paycore.service.processor.PayBaseProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <p>
 * </p>
 * User:ames wang  Date: 2017/6/28
 */
@Component
@Slf4j
public class UnfreezeTransferProcessor implements PayBaseProcessor<TransferBO,UnfreezeTransferDTO> {

    /**
     * 冻结单
     */
    @Autowired
    private FreezeOrderRepository freezeOrderRepository;

    @Override
    public PayBaseProcessor process(TransferBO transferBO, UnfreezeTransferDTO payBaseDTO) {
        //查询原单信息
        FreezeBO freezeBO = freezeOrderRepository.load(payBaseDTO.getOrigPayNo());
        if (freezeBO == null) {
            log.error("冻结单不存在 原支付单号:{}", payBaseDTO.getOrigPayNo());
            throw new PayCoreBizException(PayCoreErrorCode.FREEZE_ORDER_NO_EXIST);
        }
        if (!PayStatusEnums.SUCCESS.getCode().equals(freezeBO.getStatus())) {
            log.error("冻结订单状态不成功 不能完成 支付单号:{} 状态:{}", freezeBO.getPayNo(), freezeBO.getStatus());
            throw new PayCoreBizException(PayCoreErrorCode.FREEZE_ORDER_NO_SUC);
        }
        long bizChargeAmount = Constant.validateLong(payBaseDTO.getBizFeeAmount());
        if (freezeBO.getAmt()- Constant.validateLong(freezeBO.getDealAmt())
                < payBaseDTO.getAmt() + bizChargeAmount) {
            log.error("解冻转账金额大于可解冻金额 订单号:{} 冻结总金额:{} 解冻转账金额:{} 手续费金额:{}", freezeBO.getPayNo(),
                    freezeBO.getAmt(), payBaseDTO.getAmt(), bizChargeAmount);
            throw new PayCoreBizException(PayCoreErrorCode.OVERRUN_CONFIRM_AMOUNT);
        }
        if(freezeBO.getFreezeCode()==null){
            log.error("冻结单没有冻结码  订单号{}",freezeBO.getPayNo());
            throw new PayCoreBizException(PayCoreErrorCode.FREEZE_ORDER_NO_FREEZECODE);
        }
        DTO2BOConverter.getTransferBOByDTO(payBaseDTO, transferBO);
        transferBO.setBizChargeAmt(Constant.validateLong(payBaseDTO.getBizFeeAmount()));
        transferBO.setFreezeCode(freezeBO.getFreezeCode());
        transferBO.setBizFeeAccount(payBaseDTO.getBizFeeAccount());
        transferBO.setOldPayNo(payBaseDTO.getOrigPayNo());
        return this;
    }
}
